AUTO_CLOSE_DELAY_SECONDS = 10;//自动隐藏时间 秒
g_last_id = null;
MySpaceURL = null;
g_last_id =0;
/*(╯▔皿▔)╯ 有一大波丧失正在靠近 ㄟ(▔皿▔ㄟ)*/

var HOST = "www.oschina.net";//192.168.1.213  www.oschina.net
var HTTP = "http://";
var HTTPS = "https://";
var URL_SPLITTER = "/";
var URL_UNDERLINE = "_";
var URL_API_HOST = HTTP + HOST + URL_SPLITTER;
var LOGIN_VALIDATE_HTTP = HTTP + HOST + URL_SPLITTER + "action/api/login_validate";
var LOGIN_VALIDATE_HTTPS = HTTPS + HOST + URL_SPLITTER + "action/api/login_validate";
var NEWS_LIST = URL_API_HOST+"action/api/news_list";
var NEWS_DETAIL = URL_API_HOST+"action/api/news_detail";
var POST_LIST = URL_API_HOST+"action/api/post_list";
var POST_DETAIL = URL_API_HOST+"action/api/post_detail";
var POST_PUB = URL_API_HOST+"action/api/post_pub";
var TWEET_LIST = URL_API_HOST+"action/api/tweet_list";
var TWEET_DETAIL = URL_API_HOST+"action/api/tweet_detail";
var TWEET_PUB = URL_API_HOST+"action/api/tweet_pub";
var TWEET_DELETE = URL_API_HOST+"action/api/tweet_delete";
var ACTIVE_LIST = URL_API_HOST+"action/api/active_list";
var MESSAGE_LIST = URL_API_HOST+"action/api/message_list";
var MESSAGE_DELETE = URL_API_HOST+"action/api/message_delete";
var MESSAGE_PUB = URL_API_HOST+"action/api/message_pub";
var COMMENT_LIST = URL_API_HOST+"action/api/comment_list";
var COMMENT_PUB = URL_API_HOST+"action/api/comment_pub";
var COMMENT_REPLY = URL_API_HOST+"action/api/comment_reply";
var COMMENT_DELETE = URL_API_HOST+"action/api/comment_delete";
var SOFTWARECATALOG_LIST = URL_API_HOST+"action/api/softwarecatalog_list";
var SOFTWARETAG_LIST = URL_API_HOST+"action/api/softwaretag_list";
var SOFTWARE_LIST = URL_API_HOST+"action/api/software_list";
var SOFTWARE_DETAIL = URL_API_HOST+"action/api/software_detail"; 
var USERBLOG_LIST = URL_API_HOST+"action/api/userblog_list";
var USERBLOG_DELETE = URL_API_HOST+"action/api/userblog_delete";
var BLOG_LIST = URL_API_HOST+"action/api/blog_list";
var BLOG_DETAIL = URL_API_HOST+"action/api/blog_detail";
var BLOGCOMMENT_LIST = URL_API_HOST+"action/api/blogcomment_list";
var BLOGCOMMENT_PUB = URL_API_HOST+"action/api/blogcomment_pub";
var BLOGCOMMENT_DELETE = URL_API_HOST+"action/api/blogcomment_delete";
var MY_INFORMATION = URL_API_HOST+"action/api/my_information";
var USER_INFORMATION = URL_API_HOST+"action/api/user_information";
var USER_UPDATERELATION = URL_API_HOST+"action/api/user_updaterelation";
var USER_NOTICE = URL_API_HOST+"action/api/user_notice";
var NOTICE_CLEAR = URL_API_HOST+"action/api/notice_clear";
var FRIENDS_LIST = URL_API_HOST+"action/api/friends_list";
var FAVORITE_LIST = URL_API_HOST+"action/api/favorite_list";
var FAVORITE_ADD = URL_API_HOST+"action/api/favorite_add";
var FAVORITE_DELETE = URL_API_HOST+"action/api/favorite_delete";
var SEARCH_LIST = URL_API_HOST+"action/api/search_list";
var PORTRAIT_UPDATE = URL_API_HOST+"action/api/portrait_update";
var UPDATE_VERSION = URL_API_HOST+"MobileAppVersion.xml";
var URL_HOST = "oschina.net";
var URL_WWW_HOST = "www."+URL_HOST;
var URL_MY_HOST = "my."+URL_HOST;
var URL_TYPE_NEWS = URL_WWW_HOST + URL_SPLITTER + "news" + URL_SPLITTER;
var URL_TYPE_SOFTWARE = URL_WWW_HOST + URL_SPLITTER + "p" + URL_SPLITTER;
var URL_TYPE_QUESTION = URL_WWW_HOST + URL_SPLITTER + "question" + URL_SPLITTER;
var URL_TYPE_BLOG = URL_SPLITTER + "blog" + URL_SPLITTER;
var URL_TYPE_TWEET = URL_SPLITTER + "tweet" + URL_SPLITTER;
var URL_TYPE_ZONE = URL_MY_HOST + URL_SPLITTER + "u" + URL_SPLITTER;
var URL_TYPE_QUESTION_TAG = URL_TYPE_QUESTION + "tag" + URL_SPLITTER;

var username = "i@xioxin.com";
var pwd = "zhaoxin110";

var oscpng = new Image();
oscpng.src = "osc.png";
// if(localStorage.getItem("uid")){
//   oscapi.uid = localStorage.getItem("uid");
// };

function oscapi(url,data){
  var xml;
  $.ajax({
    type:"POST",
    url: url,
    cache:false,
    data: data,
    async:false,
    success: function(e){xml = e;},
    dataType: "xml"
  });
  return xml;
}

oscapi.portraitimg = new Image();
oscapi.portraitimg.onload = function () {
  var txcanvas=document.getElementById("txcanvas");
  var context2d = txcanvas.getContext("2d");
  context2d.fillStyle = "#EEEEFF";
  context2d.fillRect(0, 0, 19, 19);
  context2d.drawImage(oscapi.portraitimg,0,0,29,29);
  context2d.drawImage(oscpng,6,20);
  chrome.browserAction.setIcon({imageData:context2d.getImageData(6,6,19,19)});
}


oscapi.login = function(username,pwd){
  var xml = this(LOGIN_VALIDATE_HTTP,{username:username,pwd:pwd,keep_login:1});
  var $xml = $(xml);
  var errorCode = $xml.find("result errorCode").text();
  var errorMessage = $xml.find("result errorMessage").text();
  if(errorCode ==1){
    $user = $xml.find("user");
    this.uid = $user.find("uid").text();
    localStorage.setItem("uid", this.uid);
    this.name = $user.find("name").text();//昵称
    this.location = $user.find("location").text();
    this.followers = $user.find("followers").text();//关注数量
    this.fans = $user.find("fans").text();//粉丝数量
    this.score = $user.find("score").text();//积分
    this.portrait = $user.find("portrait").text();//头像
    this.portraitimg.src =oscapi.portrait;
    $notice = $xml.find("notice");
    this.notice = {
      atmeCount:$notice.find("atmeCount").text(),
      msgCount:$notice.find("msgCount").text(),
      reviewCount:$notice.find("reviewCount").text(),
      newFansCount:$notice.find("newFansCount").text()
    }
    return true;
  }else{
      console.log(errorMessage);
      return false;
  }
}
oscapi.has = function(e){
  return !(typeof this[e] === 'undefined');
}
oscapi.getUserNotice =function(){
  if(this.has('uid')){
    var xml = this(USER_NOTICE,{uid:this.uid});
    var $xml = $(xml);
      $notice = $xml.find("notice");
      this.notice = {
        atmeCount:$notice.find("atmeCount").text(),
        msgCount:$notice.find("msgCount").text(),
        reviewCount:$notice.find("reviewCount").text(),
        newFansCount:$notice.find("newFansCount").text()
      }
      return this.notice;
  }
  return false;
}
oscapi.getActiveList = function(catalog,pageIndex,pageSize){
  if(typeof catalog === 'undefined'){catalog = 1;}
  if(typeof pageIndex === 'undefined'){pageIndex = 0;}
  if(typeof pageSize === 'undefined'){pageSize = 10;}
  if(this.has('uid')){
    var xml = this(ACTIVE_LIST,{uid:this.uid,catalog:catalog,pageIndex:pageIndex,pageSize:pageSize});
    return xml;
  }
  return false;
}
oscapi.ListNotify = function(xml){
  $list = $(xml).find("activies active");
    for (var i=0;i<$list.length;i++)
    {
      var objectID = $($list[i]).find("objectID").text();
      var authorid = $($list[i]).find("authorid").text();
      notify({
        "url":"http://my.oschina.net/u/"+authorid+"/tweet/"+objectID,
        "icon":($($list[i]).find("portrait").text()).replace("_50","_100"),
        "title":"OSC - "+$($list[i]).find("author").text(),
        "body":$($list[i]).find("message").text()
      })
    }
  console.log($list);
}

oscapi.login(username,pwd);

var oldNotice=oscapi.getUserNotice();
check_new_log();
setInterval(check_new_log,10000);
function check_new_log(){
  var Notice = oscapi.getUserNotice();
  var Sum = parseInt(Notice.atmeCount)+parseInt(Notice.msgCount)+parseInt(Notice.reviewCount)+parseInt(Notice.newFansCount);
  if(!Sum){Sum = ""}
  chrome.browserAction.setBadgeText({text:Sum+""});
  if (true) {};
  var gap = {};
  gap.atmeCount    = Notice.atmeCount    - oldNotice.atmeCount;
  gap.msgCount     = Notice.msgCount     - oldNotice.msgCount;
  gap.reviewCount  = Notice.reviewCount  - oldNotice.reviewCount;
  gap.newFansCount = Notice.newFansCount - oldNotice.newFansCount;
  if(gap.atmeCount    <=0){gap.atmeCount     = 0}else{oscapi.ListNotify(oscapi.getActiveList(2,0,gap.atmeCount))};
  // if(gap.msgCount     <=0){gap.msgCount      = 0}else{oscapi.ListNotify(oscapi.getActiveList(3,0,gap.msgCount))};
  if(gap.reviewCount  <=0){gap.reviewCount   = 0}else{oscapi.ListNotify(oscapi.getActiveList(3,0,gap.reviewCount))};
  // if(gap.newFansCount <=0){gap.newFansCount  = 0}else{oscapi.ListNotify(oscapi.getActiveList())};
  oldNotice =Notice;
}


//chrome.browserAction.setIcon(img)
// for(m in arr){
//   console.log(m);
// }

// $.get("http://www.oschina.net/", function(result){
//   MySpaceURL = $(result).find("#MySpace").attr("href");
//   if(MySpaceURL){
//     console.log(MySpaceURL)
//     //start();
//   }
// });

function notify(e){
    if (window.webkitNotifications) {
        if (window.webkitNotifications.checkPermission() == 0) {
            var popup = window.webkitNotifications.createNotification(e.icon, e.title, e.body);
            console.log(popup);
            popup.onclick = function(){
              if(e.url)window.open(e.url,"_blank");
            }
            popup.ondisplay = function(event) {
                setTimeout(function() {
                    event.currentTarget.cancel();
                }, AUTO_CLOSE_DELAY_SECONDS * 1000);
            }
            if (("show" in popup)){
              popup.show();
            }
        }else{
            window.webkitNotifications.requestPermission();
            return;
        }
    }
}

// /*重新声明动弹刷新函数*/
// function check_new_log(){
//   console.log("check_new_log")
//   notifylock =!g_last_id;
//   var url = MySpaceURL+"/fetch-log?id=" + g_last_id;
//   $.get(url, function(result){
//         if(jQuery.trim(result).length > 0){
//             var first_li = $(result).first();
//             if(first_li && first_li.length>0){
//               g_last_id = first_li.attr('log');
//             }
//         }

//       if(!notifylock){
//         $list = $(result).filter("li");
        // for (var i=0;i<$list.length;i++)
        // {
        //   var url = $($list[i]).find(".ref a:contains('查看»')").attr("href");
        //   if(!url){
        //     $($list[i]).find(".user").attr("href")
        //   }


        //   notify({
        //     "url":($($list[i]).find(".time a").attr("href")),
        //     "icon":($($list[i]).find("img.SmallPortrait").attr("src")).replace("_50","_100"),
        //     "title":"OSC - "+$($list[i]).find(".user a").text(),
        //     "body":$($list[i]).find(".log").text()
        //   })
        // }
//       }
//   });
// }
// function start(){
//   check_new_log();
//   setInterval(check_new_log,1000*10)
// }



